package cn.ito.zjgsu.realm;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.ito.zjgsu.domain.Role;
import cn.ito.zjgsu.domain.UserLogin;
import cn.ito.zjgsu.domain.wrapper.RoleWrapper;
import cn.ito.zjgsu.service.RolePermissionService;
import cn.ito.zjgsu.service.UserService;
import cn.ito.zjgsu.utils.EncryptGenerator;

public class UserRealm extends AuthorizingRealm {

	@Resource
	private UserService userService;

	@Autowired
	private EncryptGenerator encryptGenerator;

	@Resource
	private RolePermissionService rolePermissionService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		String currentUsername = (String) super.getAvailablePrincipal(principals);
		UserLogin user = userService.findUserByUsername(currentUsername);

		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		if (user != null) {
			RoleWrapper roleWrapper = rolePermissionService.getRoleWrapper(user);// 从数据库取来角色名
			simpleAuthorInfo.addRole(roleWrapper.getRoleName());
			simpleAuthorInfo.addStringPermissions(roleWrapper.getStringPermissions());
			return simpleAuthorInfo;
		}

		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

		UserLogin user = userService.findUserByUsername(token.getUsername());

		if (user != null) {

			if (user.getPassword().equals(encryptGenerator.encrypt(new String(token.getPassword()), user.getSalt()))) {
				AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(),
						this.getName());
				return authcInfo;
			} else {
				throw new IncorrectCredentialsException();
			}
		} else {
			throw new UnknownAccountException();
		}

	}

}